package fr.resasante.ejb.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import fr.resasante.exception.SystemException;

/**
 * Class used for accessing the hibernate session
 * 
 * @author GEFFROY-DE-VILLEBLAN
 * 
 */
public class HibernateUtil {

	/**
	 * Instantiate the session factory
	 */
	private static final SessionFactory sessionFactory = buildSessionFactory();

	/**
	 * Initialize hibernate
	 * 
	 * @return The hibernate session
	 */
	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			final Configuration configuration = new Configuration();
			configuration.configure().setProperty("hibernate.show_sql", "false");
			final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
					.applySettings(configuration.getProperties()).buildServiceRegistry();
			final SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);
			return factory;
		} catch (final Throwable ex) {
			throw new SystemException("Initial SessionFactory creation failed.", ex);
		}
	}

	/**
	 * Get the hibernate session
	 * 
	 * @return The hibernate session
	 */
	public static Session getSession() {
		return sessionFactory.openSession();
	}

	/**
	 * Shutdowns the hibernate session
	 */
	public static void shutdown() {
		// Close caches and connection pools
		sessionFactory.close();
	}

}
